package com.example.k8s.hello.service.common.http;


import com.example.k8s.hello.common.annotation.ParamObject;
import org.springframework.core.MethodParameter;
import org.springframework.web.service.invoker.HttpRequestValues;
import org.springframework.web.service.invoker.HttpServiceArgumentResolver;

import java.lang.reflect.Field;

/**
 * 支持get请求中使用对象形式接受参数（使用自定义注解@ParamObject）
 */
public class ParamObjectResolver implements HttpServiceArgumentResolver {
    @Override
    public boolean resolve(Object argument, MethodParameter parameter, HttpRequestValues.Builder requestValues) {
        if (!parameter.hasParameterAnnotation(ParamObject.class)) {
            return false;
        }
        Class<?> clazz = argument.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            try {
                field.setAccessible(true);
                Object value = field.get(argument);
                String strValue = value == null ? "" : String.valueOf(value);
                requestValues.addRequestParameter(field.getName(), strValue);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
